//
//  BookTopicsDetailController.m
//  FreeTrip
//
//  Created by 352324497@qq.com on 15/11/27.
//  Copyright © 2015年 邓芮. All rights reserved.
//

#import "BookTopicsDetailController.h"
#import "BookTopicsDetailModel.h"
#import "BookTopicsDetailFirstCell.h"
#import "BookTopicsDetailSecondCell.h"
#import "BookPlaceDetailController.h"
@interface BookTopicsDetailController ()

@property (nonatomic, strong)NSMutableArray *modelArray;

@end

@implementation BookTopicsDetailController
//- (NSMutableArray *)modelArray
//{
//    if (_modelArray == nil)
//    {
//        self.modelArray = [NSMutableArray array];
//    }
//    return _modelArray;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorStyle = NO;
    self.navigationItem.title = self.titleName;
    self.tableView.bounces = NO;
    
    self.modelArray = [NSMutableArray array];
//    [[NetworkRequest shareNetworeRequest]netRequestForBookTopicsDetailWithUrl:url networkRequest:^(id model) {
//        self.modelArray = model;
//        NSLog( @"==============%@",_modelArray);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.tableView reloadData];
//        });
//    }];

    [self dataRequest];

    
}

-(void)dataRequest
{
    [[NetworkState shareInstance] reachablityStates:self];
    NSString *url = [NSString stringWithFormat:@"http://chanyouji.com/api/articles/%ld.json",(long)self.Id];
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
      {
          if (data == nil)
          {
              NSLog(@"数据请求失败");
              return ;
          }
          NSDictionary *zomDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
          NSString *kname = zomDic[@"name"];
          NSString *ktitle = zomDic[@"title"];
          NSString *Kimag = zomDic[@"image_url"];
          for (NSDictionary *firDic in zomDic[@"article_sections"])
          {
              BookTopicsDetailModel *model = [[BookTopicsDetailModel alloc] init];
              NSDictionary *dic = firDic[@"attraction"];
              NSNumber *num = dic[@"id"];
              NSInteger Id = [num integerValue];
              model.Id = Id;
              model.name = dic[@"name"];
              model.wName = kname;
              model.wTitle = ktitle;
              model.wImageurl = Kimag;
              [model setValuesForKeysWithDictionary:firDic];
              NSLog(@"%@",model.name);
              [self.modelArray addObject:model];
          }
          dispatch_async(dispatch_get_main_queue(), ^{
              [self.tableView reloadData];
              [MBProgressHUD hideHUDForView:self.view animated:YES];
          });
      }] resume];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.modelArray.count != 0)
    {
        return 2;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0)
    {
        return 1;
    }
    else
    {
            return self.modelArray.count - 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0)
    {
           return [BookTopicsDetailFirstCell heightForCell:self.modelArray[indexPath.row]];
    }
    else
    {
        if (indexPath.row == self.modelArray.count - 2) {
            return 0;
        }
        else
        {
            BookTopicsDetailModel *model = self.modelArray[indexPath.row + 1];
            return [BookTopicsDetailSecondCell heightForCell:model];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0)
    {
        BookTopicsDetailFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"firstCell"];
        if (cell == nil)
        {
            cell = [[BookTopicsDetailFirstCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"firstCell"];
        }
            cell.model = self.modelArray[indexPath.row];
            return cell;
    }
    else
    {
        BookTopicsDetailSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:@"secondCell"];
        if (cell == nil)
        {
            cell = [[BookTopicsDetailSecondCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"secondCell"];
        }
        cell.layer.borderColor = [UIColor blackColor].CGColor;
        cell.layer.borderWidth = 0.3;
        [cell.placeButton addTarget:self action:@selector(placeButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
            BookTopicsDetailModel *model = self.modelArray[indexPath.row  + 1];
            cell.model = model;
            return cell;
    }
}

-(void)placeButtonAction:(UIButton *)button
{
    BookTopicsDetailSecondCell *cell = (BookTopicsDetailSecondCell *)button.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    BookTopicsDetailModel *model = self.modelArray[indexPath.row  + 1];
    BookPlaceDetailController *bookPlaceDetailVC = [[BookPlaceDetailController alloc]initWithStyle:(UITableViewStylePlain)];
    bookPlaceDetailVC.name = model.name;
    bookPlaceDetailVC.Id = model.Id;
    [self.navigationController pushViewController:bookPlaceDetailVC animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
